package com.qctpos.crm.global.advice;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.qctpos.crm.global.contants.ResultCode;
import com.qctpos.crm.global.result.Result;
import com.qctpos.crm.global.utils.StringHelper;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.text.MessageFormat;


/**
 * @author chao.z
 */
@RestControllerAdvice
public class ExceptionResultAdvice  {
    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = JWTVerificationException.class)
    public Result bizExceptionHandler(JWTVerificationException jWTVerificationException){
        return Result.failure(ResultCode.INVALID_TOKEN,jWTVerificationException.getMessage());
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public Result HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception){
        String errorMsg =  MessageFormat.format(ResultCode.INVALID_REQUEST_ERROR.getMessage(), exception.getMethod(), exception.getSupportedHttpMethods());

        return Result.failure(ResultCode.INVALID_REQUEST_ERROR,errorMsg);
    }
    /**HttpRequestMethodNotSupportedException
     * 处理系统异常
     */
    @ExceptionHandler(value = Exception.class)
    public  Result exceptionHandler(Exception exception){

        String errMessage = exception.getMessage();
        if (StringHelper.isEmpty(errMessage))
        {
            errMessage=exception.toString();
        }
        return Result.failure(ResultCode.FAIL,errMessage);
    }

}